package com.hzit.search.util;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.search.dao.ItemDao;
import com.hzit.search.entity.ItemEntity;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：elasticsearch工具类
 */
@SpringBootTest
public class ESUtil {
	@Autowired
	private ElasticsearchClient client;
	@Autowired
	private ItemDao itemDao;
	//1. 创建索引结构
	@Test
	public void createIndexStruct() throws IOException {
		client.indices().create(idx->idx.index("item")
				.mappings(mappingBuilder->mappingBuilder
						.properties("title",propertyBuilder->propertyBuilder.text(textProperty->textProperty.analyzer("ik_smart").searchAnalyzer("ik_smart")))
						// .properties("title",propertyBuilder->propertyBuilder.text(textProperty->textProperty))
						.properties("price",propertyBuilder->propertyBuilder.float_(floatProperty->floatProperty))
						.properties("category",propertyBuilder->propertyBuilder.keyword(keywordProperty->keywordProperty))
						.properties("brand",propertyBuilder->propertyBuilder.keyword(brandProperty->brandProperty))
				));
	}

	//2. 导入索引库
	@Test
	public void test02() throws IOException {
		BulkRequest.Builder br = new BulkRequest.Builder();
		//2.1 查询出审核通过的sku商品列表
		List<ItemEntity> itemList = itemDao.selectList(new QueryWrapper<ItemEntity>().eq("status", "1"));
		for (ItemEntity itemEntity : itemList) {
			//2.2 得到规格信息
			String spec = itemEntity.getSpec();
			//2.3 将上面的字符串转换为map
			Map<String,Object> map = JSON.parseObject(spec, Map.class);
			//2.4 为当前的itemEntity赋值
			itemEntity.setSpecMap(map);
		}
		//2.2 遍历列表并添加到索引库中
		for (ItemEntity itemEntity : itemList) {
				br.operations(op->op.index(
						idx->idx.index("item")
							.id(itemEntity.getId() + "")
							.document(itemEntity)
				));
		}
		BulkResponse result = client.bulk(br.build());
	}
}
